package p21;

import node.ListNode;
import node.ListNodeManager;

/**
 * 21. 合并两个有序链表
 * 将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 
 * <p>
 * 示例：
 * <p>
 * 输入：1->2->4, 1->3->4
 * 输出：1->1->2->3->4->4
 */
public class Solution {
    public static void main(String[] args) {
        int[] nums1 = {1, 2, 4};
        ListNode l1 = ListNodeManager.createListNodeByArray(nums1);

        int[] nums2 = {1, 3, 4};
        ListNode l2 = ListNodeManager.createListNodeByArray(nums2);

        ListNodeManager.printlnNode(mergeTwoLists(l1, l2));
    }


    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode root = new ListNode(0);
        ListNode head = root;
        ListNode tempt = null;
        while (l1 != null && l2 != null) {
            if (l1.val <= l2.val) {
                tempt = new ListNode(l1.val);
                l1 = l1.next;
            } else {
                tempt = new ListNode(l2.val);
                l2 = l2.next;
            }
            head.next = tempt;
            head = head.next;
        }

        if (l1 != null) {
            head.next = l1;
            head = head.next;
        }

        if (l2 != null) {
            head.next = l2;
            head = head.next;
        }
        return root.next;
    }
}
